import React, {useState, useEffect} from 'react'
import {Modal} from '@/components'
import {TextareaItem, Button, Toast} from 'antd-mobile'
import pubsub from 'pubsub-js'

import './index.less'

export default function (props) {
  const [ show, setShow ] = useState(false)

  const [ content, setContent ] = useState('')

  const [ rid, setRid ] = useState(0)

  const handleClick = (rid) => {
    if (rid) {
      setRid(rid)
    } else {
      setRid(0)
    }
    setContent('')
    setShow(true)
  }

  const handleClose = () => {
    setShow(false)
  }

  const handleChange = (val) => {
    setContent(val)
  }

  const handleSubmit = () => {
    if (content) {
      props.postReply && props.postReply(content, rid)
      handleClose()
    } else {
      Toast.fail('内容不得为空')
    }
  }

  useEffect(() => {
    pubsub.subscribe('reply', (msg, rid) => {
      handleClick(rid)
    })
    return () => {
      pubsub.clearAllSubscriptions()
    }
  }, [])


  return (
    <>
      <div className='footer' onClick={handleClick}>
        评论
      </div>
      <Modal
        show={show}
        onClose={handleClose}
        styleBody={{
          height: '220px',
          bottom: '0px',
          top: 'unset'
        }}
      >
        <div className='modal-comment'>
          <TextareaItem
            rows={2}
            count={200}
            onChange={handleChange}
          />
          <Button className='comment-btn' type='warning' onClick={handleSubmit}>评论</Button>
        </div>
      </Modal>
    </>
  )
}
